$.ajaxSetup(
{
    cache : false
}
);
(function ($)
{
    //导航菜单
    $.fn.duxMenu = function (options)
    {
        var defaults =
        {
            json : {},
            sidebar : '#sidebar',
            menu : '#menu',
            bread : '#bread',
            scrollbar : true
        }
        var options = $.extend(defaults, options);
        this.each(function ()
        {
            var nav = $(this);
            //主导航
            var navHtml = '';
            for (var i in options.json)
            {
                navHtml += '<li><a href="javascript:;" data="' + i + '">' + options.json[i].name + '</a></li>';
            }
            nav.html(navHtml);
            if (options.scrollbar)
            {
                var menuScrollbar = $(options.menu).jScrollPane();
                var menuApi = menuScrollbar.data('jsp');
                $(window).bind('resize', function ()
                {
                    menuApi.reinitialise();
                }
                );
            }
            //菜单导航
            nav.find("a").click(function ()
            {
                var label = $(this).attr('data');
                var list = options.json[label]['menu'];
                menuShow(list, label);
                $(options.menu).find('li a:first').click();
            }
            );
            //菜单显示
            function menuShow(list, label)
            {
                var html = '';
                for (var i in list)
                {
                    if ($.isArray(list[i].name))
                    {
                        list[i].name = list[i].name[0];
                    }
                    html += '<h2>' + list[i].name + '</h2><ul>';
                    var menu = list[i].menu;
                    for (var o in menu)
                    {
                        if (menu == '' || menu == null)
                        {
                            continue;
                        }
                        html += '<li><a href="javascript:;" data="' + menu[o].url + '" top="' + label + '">';
                        if (menu[o].ico != null)
                        {
                            html += '<i class="u-icon">' + menu[o].ico + '</i> ';
                        }
                        if ($.isArray(menu[o].name))
                        {
                            menu[o].name = menu[o].name[0];
                        }
                        html += '<span>' + menu[o].name + '</span></a></li>';
                    }
                    html += '</ul>';
                }
                if (options.scrollbar)
                {
                    menuApi.getContentPane().html(html);
                    menuApi.reinitialise();
                }
                else
                {
                    $(options.menu).html(html);
                }
            }
            //菜单点击
            $(options.menu).on('click', 'a', function ()
            {
                $(options.menu).find('a').removeClass("current");
                $(this).addClass('current');
                $('iframe').attr('src', $(this).attr('data'));
            }
            );
            
            //初次刷新
            nav.find("a:first").click();
        }
        );
    };
    //表格处理
    $.fn.duxTable = function (options)
    {
        var defaults =
        {
            selectAll : '#selectAll',
            deleteUrl : ''
        }
        var options = $.extend(defaults, options);
        this.each(function ()
        {
            var table = this;
            //处理多选单选
            $(options.selectAll).click(function ()
            {
                if (!!$(options.selectAll).attr("checked"))
                {
                    $(table).find("[name='id[]']").each(function ()
                    {
                        $(this).attr("checked", 'true');
                    }
                    )
                }
                else
                {
                    $(table).find("[name='id[]']").each(function ()
                    {
                        $(this).removeAttr("checked");
                    }
                    )
                }
                
            }
            );
            //处理删除
            $(table).find('.u-del').click(function ()
            {
                var obj = this;
                var div = $(obj).parent().parent();
                var url = '';
                if (options.deleteUrl == '')
                {
                    url = $(obj).attr('url');
                }
                else
                {
                    url = options.deleteUrl;
                }
                $.dialog.confirm('你确认删除操作？', function ()
                {
                    $.post(url,
                    {
                        data : $(obj).attr('data')
                    }, function (json)
                    {
                        if (json.status == 'y')
                        {
                            div.remove();
                            $.dialog.tips(json.info, 1);
                        }
                        else
                        {
                            $.dialog.tips(json.info, 3);
                        }
                    }, 'json');
                }, function ()
                {
                    return;
                }
                );
            }
            );
            //处理ajax编辑
            $(table).find('.u-edit').click(function ()
            {
                var oldText = $(this).text();
                var width = $(this).attr('width');
                var obj = this;
                var input = $(obj).find('input');
                var url = $(obj).attr('url');
                var name = $(obj).attr('name');
                if (input.length == 0)
                {
                    var html = '<input class="u-ipt" style="width:' + width + 'px;" value="' + oldText + '" type="text" />';
                    $(obj).html(html);
					input = $(obj).find('input');
                }
				input.focus();
                input.blur(function ()
                {
                    text = input.val();
                    $.post(url,
                    {
                        name : name,
                        data : text
                    }, function (json)
                    {
                        if (json.status == 'y')
                        {
                            $(obj).text(json.info);
                        }
                        else
                        {
                            input.addClass('u-tta-err');
                            $.dialog.tips(json.info);
                        }
                    }, 'json');
                }
                );
            }
            );
        }
        );
    };
    //表单处理
    $.fn.duxForm = function (options)
    {
        var defaults =
        {
            status : '#status',
            returnUrl : ''
        }
        var options = $.extend(defaults, options);
        this.each(function ()
        {
            var form = this;
            //添加关联KEY
            var key = new Date();
            key = key.getTime();
            if ($("#relation_key").length > 0)
            {
                if ($("#relation_key").val() == null)
                {
                    $("#relation_key").val(key);
                }
            }
            else
            {
                $(form).append('<input name="relation_key" id="relation_key" type="hidden" value="' + key + '" />');
            }
            //表单处理
            $(form).Validform(
            {
                ajaxPost : true,
                postonce : true,
                tiptype : function (msg, o, cssctl)
                {
                    if (!o.obj.is("form"))
                    {
                        var objtip = o.obj.siblings("p");
                        cssctl(objtip, o.type);
                        objtip.text(msg);
                    }
                    else
                    {
                        $(options.status).text(msg);
                    }
                },
                callback : function (data)
                {
                    $(options.status).click();
                    $(options.status).removeClass('status-err');
                    if (data.status == "y")
                    {
                        if (options.returnUrl == null || options.returnUrl == '')
                        {
                            $(options.status).html(data.info + '马上为您重新载入！');
                            window.setTimeout(function ()
                            {
                                window.location.reload();
                            }, 3000);
                        }
                        else
                        {
                            var html = ' 您可以 <a href="javascript:window.location.reload(); ">刷新</a> 或 <a href="' + options.returnUrl + '">返回</a>，无操作5秒后会返回。';
                            $(options.status).html(data.info + html);
                            window.setTimeout(function ()
                            {
                                window.location.href = options.returnUrl;
                            }, 5000);
                        }
                    }
                    else
                    {
                        $(options.status).addClass('status-err');
                        $(options.status).html(data.info);
                    }
                }
            }
            );
            
        }
        );
    };
    
    //编辑器调用
    $.fn.duxEditor = function (options)
    {
        var defaults =
        {
            uploadUrl : rootUrl + 'index.php?r=admin/Upload/index',
            fileUrl : '',
            uploadParams :
            {
                relation_key : $('#relation_key').val()
            },
            config : {}
        }
        var options = $.extend(defaults, options);
        this.each(function ()
        {
            //编辑器
            var id = this;
            var editorConfig =
            {
                allowFileManager : false,
                uploadJson : options.uploadUrl,
                fileManagerJson : options.fileUrl,
                extraFileUploadParams : options.uploadParams,
                afterBlur : function ()
                {
                    this.sync();
                }
            };
            editorConfig = $.extend(editorConfig, options.config);
            var editor = KindEditor.create(id, editorConfig);
        }
        );
    };
    
    //颜色
    $.fn.duxColor = function (options)
    {
        var defaults = {}
        var options = $.extend(defaults, options);
        this.each(function ()
        {
            $(this).soColorPacker();
        }
        );
    };
    
    //上传调用
    $.fn.duxFileUpload = function (options)
    {
        var defaults =
        {
            uploadUrl : rootUrl + 'index.php?r=admin/Upload/index',
            uploadParams :
            {
                relation_key : $('#relation_key').val()
            },
            complete : function ()  {},
            uploadParamsCallback : function ()  {},
            type : ''
        }
        var options = $.extend(defaults, options);
        this.each(function ()
        {
            var upButton = $(this);
            var urlVal = upButton.attr('data');
            urlVal = $('#' + urlVal);
            var buttonText = upButton.text();
            var preview = upButton.attr('preview');
            preview = $('#' + preview);
            /* 图片预览 */
            preview.click(function ()
            {
                if (urlVal.val() == '')
                {
                    $.dialog.tips('没有发现已上传图片！', 2);
                }
                else
                {
                    window.open(urlVal.val());
                }
                return;
            }
            );
            /*创建上传*/
            var uploader = new plupload.Uploader(
                {
                    runtimes : 'html5,flash,html4',
                    browse_button : upButton.attr('id'),
                    url : options.uploadUrl,
                    flash_swf_url : baseDir + '/upload/Moxie.swf',
                    filters :
                    {
                        mime_types : [
                            {
                                title : "上传文件",
                                extensions : options.type
                            }
                        ]
                    }
                }
                );
            uploader.init();
            uploader.bind('FilesAdded', function (up, files)
            {
                if (files.length > 1)
                {
                    uploader.splice();
                    $.dialog.tips('一次只能上传一个文件！', 2);
                    return false;
                }
                else
                {
                    var ParamsCallback = options.uploadParamsCallback();
                	uploader.settings.multipart_params = $.extend(options.uploadParams, ParamsCallback);
                    uploader.start(true);
                    buttonStatus(false);
                    return true;
                }
            }
            );
            uploader.bind('UploadProgress', function (up, file)
            {
                upButton.text('上传：' + file.percent + '%');
            }
            );
            uploader.bind('FileUploaded', function (up, file, data)
            {
                data = data.response;
                data = eval('(' + data + ')');
                if (data.error)
                {
                    uploader.splice();
                    $.dialog.tips(data.message, 2);
                    buttonStatus(true);
                    return false;
                }
                else
                {
                    urlVal.val(data.url);
                    options.complete(data.info, urlVal);
                    return true;
                }
            }
            );
            uploader.bind('UploadComplete', function (up, files)
            {
                upButton.text(buttonText);
                buttonStatus(true);
            }
            );
            uploader.bind('Error', function (up, err)
            {
                alert(err.message);
            }
            );
            /*按钮状态*/
            function buttonStatus(status)
            {
                if (status)
                {
                    uploader.disableBrowse(false);
                    $(upButton).removeClass('s-btn-c4');
                }
                else
                {
                    uploader.disableBrowse(true);
                    $(upButton).addClass('s-btn-c4');
                }
                
            }
        }
        );
    };
    
    //多图上传
    $.fn.duxMultiUpload = function (options)
    {
        var defaults =
        {
            uploadUrl : rootUrl + 'index.php?r=admin/Upload/index',
            fileList : rootUrl + 'index.php?r=admin/Attachment/fileList',
            uploadParams :
            {
                relation_key : $('#relation_key').val()
            },
            complete : function ()  {},
            uploadParamsCallback : function ()  {},
            type : '',
            UploadMaxNum : 20
        }
        var options = $.extend(defaults, options);
        this.each(function ()
        {
            var upButton = $(this);
            var dataName = upButton.attr('data');
            var div = $('#' + dataName);
            var data = div.attr('data');
            var buttonText = upButton.text();
            //获取列表
            if (data != null)
            {
                $.post(options.fileList,
                {
                    id : data
                }, function (json)
                {
                    if (json.status == 'y')
                    {
                        for (var i in json.info)
                        {
                            htmlList(json.info[i].info);
                        };
                        if (json.info[1].info != null)
                        {
                            div.sortable().on('sortupdate', function ()  {}
                            
                            );
                        }
                    }
                }, 'json');
            }
            /*创建上传*/
            var uploader = new plupload.Uploader(
                {
                    runtimes : 'html5,flash,html4',
                    browse_button : upButton.attr('id'),
                    url : options.uploadUrl,
                    flash_swf_url : baseDir + '/upload/Moxie.swf',
                    filters :
                    {
                        mime_types : [
                            {
                                title : "上传文件",
                                extensions : options.type
                            }
                        ]
                    }
                }
                );
            uploader.init();
            uploader.bind('FilesAdded', function (up, files)
            {
                num = div.find('li').length;
                if (num >= options.UploadMaxNum)
                {
                    uploader.splice();
                    $.dialog.tips('最多只能上传' + options.UploadMaxNum + '张图片', 2);
                    return false;
                }
                if (files.length > options.UploadMaxNum)
                {
                    uploader.splice();
                    $.dialog.tips('最多只能选择' + options.UploadMaxNum + '张图片', 2);
                    return false;
                }
                var ParamsCallback = options.uploadParamsCallback();
                uploader.settings.multipart_params = $.extend(options.uploadParams, ParamsCallback);
                uploader.start(true);
                buttonStatus(false);
                return true;
            }
            );
            uploader.bind('UploadProgress', function (up, file)
            {
                upButton.text('上传：' + file.percent + '%');
            }
            );
            uploader.bind('FileUploaded', function (up, file, data)
            {
                data = data.response;
                data = eval('(' + data + ')');
                if (data.error)
                {
                    uploader.splice();
                    $.dialog.tips(data.message, 2);
                    buttonStatus(true);
                    return false;
                }
                else
                {
                    htmlList(data.info);
                    options.complete(data.info, file);
                    return true;
                }
            }
            );
            uploader.bind('UploadComplete', function (up, files)
            {
                upButton.text(buttonText);
                buttonStatus(true);
                div.sortable().on('sortupdate', function ()  {}
                
                );
            }
            );
            uploader.bind('Error', function (up, err)
            {
                alert(err.message);
            }
            );
            /*按钮状态*/
            function buttonStatus(status)
            {
                if (status)
                {
                    uploader.disableBrowse(false);
                    $(upButton).removeClass('s-btn-c4');
                }
                else
                {
                    uploader.disableBrowse(true);
                    $(upButton).addClass('s-btn-c4');
                }
                
            }
            //处理上传列表
            function htmlList(file)
            {
                var html = '<li>\
                                        					<a class="close" href="javascript:;" onclick="$(this).parent().remove();">×</a>\
                                        					<div class="img"><span class="pic"><img src="' + file.url + '" width="80" height="80" /></span></div>\
                                        					<div class="title">\
                                        					<input name="' + dataName + '[id][]" type="hidden" value="' + file.file_id + '" />\
                                        					<input name="' + dataName + '[title][]" type="text" value="' + file.title + '" />\
                                        					</div>\
                                        				</li>';
                options.complete(file, upButton);
                div.append(html);
            }
            //处理删除
            div.on('click', '.close', function ()
            {
                $(this).parent().remove();
            }
            );
            
        }
        );
    };
    //联动菜单
    $.fn.duxLinkMenu = function (options)
    {
        var defaults = {}
        var options = $.extend(defaults, options);
        this.each(function ()
        {
            var menu = this;
            var url = $(menu).attr('data');
            var id = $(menu).attr('id');
            var name = $(menu).attr('name');
            if (url == '' || url == null)
            {
                return false;
            }
            //选择绑定
            $(menu).parent().on('change', 'select', function ()
            {
                var subMenu = $(this);
                var pid = subMenu.val();
                if (pid == '' || pid == null)
                {
                    return false;
                }
                subMenu.nextAll('select').remove();
                $.post(url,
                {
                    pid : pid
                }, function (json)
                {
                    if (json.status == 'y' && json.info != '')
                    {
                        //去处属性
                        $(menu).parent().find('select').attr('name', '');
                        $(menu).parent().find('select').attr('id', '');
                        //添加选项
                        var html = '<select class="u-slt" name="' + name + '" id="' + id + '">\
                                                        						<option value="">请选择</option>';
                        for (var i in json.info)
                        {
                            html += '<option value="' + json.info[i].id + '">' + json.info[i].name + '</option>';
                        }
                        html += '</select>';
                        subMenu.after(html);
                    }
                    else
                    {
                        return false;
                    }
                }, 'json');
            }
            );
            
        }
        );
    };
    
    //表单页面处理
    $.fn.duxFormPage = function (options)
    {
        var defaults =
        {
            uploadUrl : rootUrl + 'index.php?r=admin/Upload/index',
            fileList : rootUrl + 'index.php?r=admin/Attachment/fileList',
            uploadComplete : function ()  {},
            uploadParamsCallback : function ()  {},
            UploadMaxNum : 20,
            returnUrl : ''
        }
        var options = $.extend(defaults, options);
        this.each(function ()
        {
            var form = this;
            form = $(form);
            //表单处理
            form.duxForm(
            {
                status : '#status',
                returnUrl : options.returnUrl
            }
            );
            //多图片上传
            if ($(".u-multi-upload").length > 0)
            {
                form.find('.u-multi-upload').duxMultiUpload(
                {
                    type : 'jpg,gif,png,bmp,jpeg',
                    uploadUrl : options.uploadUrl,
                    fileList : options.fileList,
                    complete : options.uploadComplete,
                    uploadParamsCallback : options.uploadParamsCallback,
                    UploadMaxNum : options.UploadMaxNum
                }
                );
            }
            //图片上传
            if ($(".u-img-upload").length > 0)
            {
                form.find('.u-img-upload').duxFileUpload(
                {
                    type : 'jpg,gif,png,bmp,jpeg',
                    uploadUrl : options.uploadUrl,
                    complete : options.uploadComplete,
                    uploadParamsCallback : options.uploadParamsCallback
                }
                );
            }
            //文件上传
            if ($(".u-file-upload").length > 0)
            {
                form.find('.u-file-upload').duxFileUpload(
                {
                    type : '*',
                    uploadUrl : options.uploadUrl,
                    complete : options.uploadComplete,
                    uploadParamsCallback : options.uploadParamsCallback
                }
                );
            }
            //编辑器
            if ($(".u-editor").length > 0)
            {
                form.find('.u-editor').duxEditor();
            }
            //颜色
            if ($(".u-color").length > 0)
            {
                form.find('.u-color').duxColor();
            }
            //时间选择
            if ($(".u-time").length > 0)
            {
                form.find('.u-time').calendar(
                {
                    format : 'yyyy-MM-dd HH:mm:ss'
                }
                );
            }
            //联动菜单
            if ($(".u-linkage").length > 0)
            {
                form.find('.u-linkage').duxLinkMenu();
            }
            //TAB菜单
            if ($(".u-tabs").length > 0)
            {
                $(".u-tabs li .tab-a").powerSwitch(
                {
                    classAdd : "tab-on"
                }
                );
            }
        }
        );
    };
    
    //AJAX操作带确认
    $.fn.duxAjaxConfirm = function (options)
    {
        var defaults =
        {
            url : '',
            content : '',
            params : function ()  {},
            success : function ()  {},
            failure : function ()  {}
        }
        var options = $.extend(defaults, options);
        this.each(function ()
        {
            var obj = this;
            $(obj).click(function ()
            {
                var params = options.params(obj);
                debug(params);
                $.dialog.confirm(options.content, function ()
                {
                    $.post(options.url, params, function (json)
                    {
                        if (json.status == 'y')
                        {
                            options.complete(json.info, obj);
                            $.dialog.tips(json.info, 2);
                        }
                        else
                        {
                            options.failure(json.info, obj);
                            $.dialog.tips(json.info, 2);
                        }
                    }, 'json');
                    
                }
                );
            }
            );
            
        }
        );
    };
}
)(jQuery);
